<template>
  <div class="light-control-container">
    <div class="light-control" style="position: relative;">
      <h3>补光灯1</h3>
      <button 
        id="light1ControlBtn" 
        @click="toggleLight(1)" 
        class="round-btn"
        :style="getButtonStyle(1)"
      >
        {{ getButtonText(1) }}
      </button>
      <div id="light1Status" class="light-status">状态: {{ getStatusText(1) }}</div>
    </div>

    <div class="light-control">
      <h3>补光灯2</h3>
      <button 
        id="light2ControlBtn" 
        @click="toggleLight(2)" 
        class="round-btn"
        :style="getButtonStyle(2)"
      >
        {{ getButtonText(2) }}
      </button>
      <div id="light2Status" class="light-status">状态: {{ getStatusText(2) }}</div>
    </div>

    <div class="light-control">
      <h3>补光灯3</h3>
      <button 
        id="device3ControlBtn" 
        @click="toggleLight(3)" 
        class="round-btn"
        :style="getButtonStyle(3)"
      >
        {{ getButtonText(3) }}
      </button>
      <div id="device3Status" class="light-status">状态: {{ getStatusText(3) }}</div>
    </div>

    <div class="light-control">
      <h3>补光灯4</h3>
      <button 
        id="device4ControlBtn" 
        @click="toggleLight(4)" 
        class="round-btn"
        :style="getButtonStyle(4)"
      >
        {{ getButtonText(4) }}
      </button>
      <div id="device4Status" class="light-status">状态: {{ getStatusText(4) }}</div>
    </div>

    <div class="light-control">
      <h3>排气扇</h3>
      <button 
        id="device5ControlBtn" 
        @click="toggleLight(5)" 
        class="round-btn"
        :style="getButtonStyle(5)"
      >
        {{ getButtonText(5) }}
      </button>
      <div id="device5Status" class="light-status">状态: {{ getStatusText(5) }}</div>
    </div>

    <div class="light-control">
      <h3>湿帘泵</h3>
      <button 
        id="device6ControlBtn" 
        @click="toggleLight(6)" 
        class="round-btn"
        :style="getButtonStyle(6)"
      >
        {{ getButtonText(6) }}
      </button>
      <div id="device6Status" class="light-status">状态: {{ getStatusText(6) }}</div>
    </div>
  </div>
</template>

<script setup lang="ts">

import { ref, onMounted } from 'vue'

// 设备状态数组，1表示打开，0表示关闭
const deviceStatus = ref<number[]>([0, 0, 0, 0, 0, 0]) // 对应6个设备的状态
let token = ref<string | null>(null)

// 登录并获取token
const login = async () => {
  const loginData = {
    username: '15611530008',
    password: 'Test1234'
    // 移除captchaVerification参数
  }

  try {
    const response = await fetch('https://things.ysiot.net:18080/api/auth/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(loginData)
    })

    if (response.ok) {
      const result = await response.json()
      // 根据API返回结构调整token提取方式
      token.value = result.access_token || result.accessToken || result.token || result

      return true
    } else {
      const errorText = await response.text()
      console.error('登录失败:', response.status, errorText)
      return false
    }
  } catch (error) {
    console.error('登录请求出错:', error)
    return false
  }
}

// 控制设备
const controlDevice = async (deviceIndex: number, status: number) => {
  // 如果没有token，先登录获取token
  if (!token.value) {
    const loginSuccess = await login()
    if (!loginSuccess) {
      alert('登录失败，无法控制设备')
      return false
    }
  }

  // 设备参数配置
  const deviceParams = [
    { // 补光灯1
      DevCode: "ysiot26001000992",
      FieldName: "ChannelParamSet12:Status",
      Value: status
    },
    { // 补光灯2
      DevCode: "ysiot26001000992",
      FieldName: "ChannelParamSet13:Status",
      Value: status
    },
    { // 补光灯3
      DevCode: "ysiot26001000992",
      FieldName: "ChannelParamSet14:Status",
      Value: status
    },
    { // 补光灯4
      DevCode: "ysiot26001000992",
      FieldName: "ChannelParamSet15:Status",
      Value: status
    },
    { // 排气扇
      DevCode: "ysiot26001000992",
      FieldName: "ChannelParamSet11:Status",
      Value: status
    },
    { // 湿帘泵
      DevCode: "ysiot26001000992",
      FieldName: "ChannelParamSet10:Status",
      Value: status
    },
    { // 设备6
      DevCode: "ysiot26001000992",
      FieldName: "ChannelParamSet17:Status",
      Value: status
    }
  ]

  try {
    const response = await fetch('https://things.ysiot.net:18080/api/v1/dev/SetProperty', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Authorization': 'Bearer ' + token.value // 使用正确的认证头格式
      },
      body: JSON.stringify(deviceParams[deviceIndex - 1])
    })

    if (response.ok) {
      const result = await response.json()
      // console.log('设备控制成功:', result)
      // 更新状态
      deviceStatus.value[deviceIndex - 1] = status
      return true
    } else {
      const errorText = await response.text()
      console.error('设备控制失败:', response.status, errorText)
      alert('设备控制失败: ' + errorText)
      return false
    }
  } catch (error) {
    console.error('设备控制请求出错:', error)
    alert('设备控制请求出错: ' + (error as Error).message)
    return false
  }
}

// 切换设备状态
const toggleLight = async (deviceIndex: number) => {
  const newStatus = deviceStatus.value[deviceIndex - 1] === 0 ? 1 : 0
  const success = await controlDevice(deviceIndex, newStatus)
  if (success) {
    deviceStatus.value[deviceIndex - 1] = newStatus
  }
}

// 获取按钮文本
const getButtonText = (deviceIndex: number) => {
  return deviceStatus.value[deviceIndex - 1] === 1 ? '关闭' : '打开'
}

// 获取状态文本
const getStatusText = (deviceIndex: number) => {
  return deviceStatus.value[deviceIndex - 1] === 1 ? '打开' : '关闭'
}

// 获取按钮样式
const getButtonStyle = (deviceIndex: number) => {
  if (deviceStatus.value[deviceIndex - 1] === 1) {
    // 打开状态，使用亮色（类似于灯光亮的颜色）
    return {
      background: 'linear-gradient(145deg, #00ff00, #00cc00)'
    }
  } else {
    // 关闭状态，使用暗色或灰色
    return {
      background: 'linear-gradient(145deg, #666666, #444444)'
    }
  }
}

onMounted(() => {
  // 初始化所有设备状态为关闭
  const initialStatus: number[] = [0, 0, 0, 0, 0, 0]
  for (let i = 0; i < initialStatus.length; i++) {
    deviceStatus.value[i] = initialStatus[i]
  }
})
</script>

<style scoped>
/* 组件样式已在引入的CSS文件中定义 */
.light-control-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  padding: 10px;
}

.light-control {
  text-align: center;
  margin: 10px;
  flex: 0 0 calc(33.333% - 20px);
}

.light-control h3 {
  color: #0ff;
  margin-bottom: 8px;
  font-size: 12px;
}

.light-control .round-btn {
  width: 45px;
  height: 45px;
  border-radius: 50%;
  background: linear-gradient(145deg, #666666, #444444);
  color: white;
  border: none;
  font-size: 12px;
  cursor: pointer;
  margin-bottom: 6px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.light-control .round-btn:hover {
  transform: scale(1.05);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.4);
}

.light-control .round-btn:active {
  transform: scale(0.95);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.light-control .round-btn::after {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(255,255,255,0.4) 0%, rgba(255,255,255,0) 70%);
  transform: rotate(30deg);
  transition: all 0.3s ease;
}

.light-control .round-btn:hover::after {
  transform: rotate(30deg) translate(20%, 20%);
}

.light-status {
  color: #fff;
  font-size: 10px;
}
</style>
